"""
插件框架高级功能集成示例
演示权限控制、沙箱、签名验证、自动更新、国际化和操作录制等功能
"""

import os
import sys
import tempfile
from typing import Dict, Any

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

# 导入插件框架核心组件
from plugin_framework.plugin_manager import PluginManager
from plugin_framework.api_context import APIContext
from plugin_framework.hook_hub import HookHub

# 导入安全组件
from plugin_framework.security.permissions import PermissionManager, Permission
from plugin_framework.security.sandbox import SandboxManager
from plugin_framework.security.signing import PluginSecurityManager

# 导入市场组件
from plugin_framework.market.updater import PluginMarketClient

# 导入国际化组件
from plugin_framework.i18n.localization import LocalizationManager

# 导入录制组件
from plugin_framework.recorder.operation_recorder import OperationRecorder, OperationPlayer


class AdvancedPluginFramework:
    """高级插件框架"""
    
    def __init__(self, plugin_dir: str = "./plugins"):
        # 核心组件
        self.api_context = APIContext("AdvancedFramework")
        self.hook_hub = HookHub()
        self.plugin_manager = PluginManager(plugin_dir, self.api_context, self.hook_hub)
        
        # 安全组件
        self.permission_manager = PermissionManager()
        self.sandbox_manager = SandboxManager(self.permission_manager)
        self.security_manager = PluginSecurityManager("./keys")
        
        # 市场组件
        self.market_client = PluginMarketClient("https://plugins.example.com/api")
        
        # 国际化组件
        self.localization_manager = LocalizationManager("./locales")
        
        # 录制组件
        self.operation_recorder = OperationRecorder()
        self.operation_player = OperationPlayer(self.operation_recorder)
        
        # 初始化安全权限
        self._setup_default_permissions()
        
        # 注册系统钩子
        self._register_system_hooks()
    
    def _setup_default_permissions(self):
        """设置默认权限"""
        # 为hello_plugin授予权限
        self.permission_manager.grant_permission("hello_plugin", Permission.NETWORK_CONNECT)
        self.permission_manager.grant_permission("hello_plugin", Permission.UI_WINDOW)
        
        # 注册受信任插件
        public_key = self.security_manager.signature_manager.load_public_key("hello_plugin")
        if public_key:
            self.security_manager.register_trusted_plugin("hello_plugin", public_key)
    
    def _register_system_hooks(self):
        """注册系统钩子"""
        # 插件加载钩子
        def on_plugin_loaded(plugin_name: str):
            print(self.localization_manager.translate("plugin_loaded", plugin_name=plugin_name))
            # 记录操作
            self.operation_recorder.record_operation(
                "system_event", "framework", "plugin_loaded", 
                {"plugin_name": plugin_name}
            )
        
        # 插件卸载钩子
        def on_plugin_unloaded(plugin_name: str):
            print(self.localization_manager.translate("plugin_unloaded", plugin_name=plugin_name))
            # 记录操作
            self.operation_recorder.record_operation(
                "system_event", "framework", "plugin_unloaded", 
                {"plugin_name": plugin_name}
            )
        
        self.hook_hub.on('plugin_loaded', on_plugin_loaded)
        self.hook_hub.on('plugin_unloaded', on_plugin_unloaded)
    
    def load_plugin_safely(self, plugin_name: str) -> Any:
        """安全地加载插件"""
        try:
            # 验证插件签名
            plugin_dir = os.path.join(self.plugin_manager.plugin_dir, plugin_name)
            if not self.security_manager.verify_plugin_integrity(plugin_name, plugin_dir):
                raise SecurityError(f"Plugin '{plugin_name}' signature verification failed")
            
            # 创建沙箱环境
            sandbox = self.sandbox_manager.create_sandbox(plugin_name)
            
            # 加载插件
            plugin = self.plugin_manager.load(plugin_name)
            
            # 注入沙箱环境到插件上下文
            context = plugin.get_context()
            if context:
                context.set_config('sandbox', sandbox)
            
            return plugin
        except Exception as e:
            print(f"Error loading plugin safely: {e}")
            return None
    
    def run_plugin_with_recording(self, plugin_name: str, *args, **kwargs) -> Any:
        """录制模式下运行插件"""
        # 开始录制
        self.operation_recorder.start_recording()
        
        try:
            # 获取插件
            plugin = self.plugin_manager.get(plugin_name)
            if not plugin:
                plugin = self.load_plugin_safely(plugin_name)
                if not plugin:
                    raise RuntimeError(f"Failed to load plugin: {plugin_name}")
            
            # 记录操作开始
            self.operation_recorder.record_operation(
                "plugin_action", plugin_name, "run_start", 
                {"args": args, "kwargs": kwargs}
            )
            
            # 运行插件
            start_time = time.time()
            result = plugin.run(*args, **kwargs)
            duration = time.time() - start_time
            
            # 记录操作结束
            self.operation_recorder.record_operation(
                "plugin_action", plugin_name, "run_complete", 
                {"args": args, "kwargs": kwargs, "result": str(result)},
                duration=duration
            )
            
            return result
        except Exception as e:
            # 记录错误
            self.operation_recorder.record_operation(
                "error", plugin_name, "run_error", 
                {"error": str(e)}
            )
            raise
        finally:
            # 停止录制
            self.operation_recorder.stop_recording()
    
    def check_for_plugin_updates(self) -> Dict[str, Any]:
        """检查插件更新"""
        updates = {}
        
        # 获取已加载的插件
        loaded_plugins = self.plugin_manager.get_loaded_names()
        
        for plugin_name in loaded_plugins:
            try:
                # 获取插件配置
                config = self.plugin_manager.get_config(plugin_name)
                if config:
                    # 检查更新
                    update_info = self.market_client.updater.check_for_updates(
                        plugin_name, config.version
                    )
                    if update_info and update_info.needs_update:
                        updates[plugin_name] = update_info
            except Exception as e:
                print(f"Error checking updates for {plugin_name}: {e}")
        
        return updates
    
    def update_plugin(self, plugin_name: str) -> bool:
        """更新插件"""
        try:
            # 获取插件配置
            config = self.plugin_manager.get_config(plugin_name)
            if not config:
                return False
            
            # 检查更新
            update_info = self.market_client.updater.check_for_updates(
                plugin_name, config.version
            )
            if not update_info or not update_info.needs_update:
                return False
            
            # 下载更新
            update_file = self.market_client.updater.download_update(update_info)
            if not update_file:
                return False
            
            # 应用更新
            plugin_dir = os.path.join(self.plugin_manager.plugin_dir, plugin_name)
            success = self.market_client.updater.apply_update(
                plugin_name, update_file, plugin_dir
            )
            
            if success:
                # 重新加载插件
                self.plugin_manager.reload(plugin_name)
                print(self.localization_manager.translate("update_installed"))
            
            return success
        except Exception as e:
            print(f"Error updating plugin {plugin_name}: {e}")
            return False
    
    def set_language(self, locale_code: str):
        """设置语言环境"""
        if locale_code in self.localization_manager.get_available_locales():
            self.localization_manager.set_locale(locale_code)
            print(f"Language set to: {locale_code}")
        else:
            print(f"Unsupported locale: {locale_code}")
    
    def get_recorded_operations(self):
        """获取录制的操作"""
        return self.operation_recorder.get_records()
    
    def save_recording(self, file_path: str):
        """保存录制"""
        return self.operation_recorder.save_to_file(file_path)
    
    def load_recording(self, file_path: str):
        """加载录制"""
        return self.operation_recorder.load_from_file(file_path)
    
    def play_recording(self, speed: float = 1.0):
        """回放录制"""
        records = self.operation_recorder.get_records()
        return self.operation_player.play(records, speed)
    
    def generate_documentation(self):
        """生成文档"""
        try:
            from plugin_framework.docs.generator import DocumentationGenerator
            doc_gen = DocumentationGenerator("./generated_docs")
            
            # 获取已加载的插件
            plugins = self.plugin_manager.get_all()
            
            # 生成完整文档
            files = doc_gen.generate_full_documentation(self.plugin_manager, plugins)
            print(f"Generated documentation files: {files}")
            return files
        except Exception as e:
            print(f"Error generating documentation: {e}")
            return []


# 自定义异常
class SecurityError(Exception):
    """安全相关异常"""
    pass


# 使用示例
if __name__ == "__main__":
    import time
    
    print("=== 高级插件框架演示 ===")
    
    # 创建框架实例
    framework = AdvancedPluginFramework("./plugins")
    
    # 设置语言为中文
    framework.set_language("zh_CN")
    
    # 安全加载插件
    print("\n1. 安全加载插件...")
    plugin = framework.load_plugin_safely("hello_plugin")
    if plugin:
        print(f"✓ 插件加载成功: {plugin}")
    
    # 录制模式运行插件
    print("\n2. 录制模式运行插件...")
    try:
        result = framework.run_plugin_with_recording("hello_plugin", name="RecorderTest")
        print(f"✓ 插件运行结果: {result}")
    except Exception as e:
        print(f"✗ 插件运行失败: {e}")
    
    # 检查更新
    print("\n3. 检查插件更新...")
    updates = framework.check_for_plugin_updates()
    if updates:
        for plugin_name, update_info in updates.items():
            print(f"  {plugin_name}: {update_info.current_version} -> {update_info.latest_version}")
    else:
        print("  没有可用更新")
    
    # 显示录制的操作
    print("\n4. 录制的操作:")
    records = framework.get_recorded_operations()
    for record in records:
        print(f"  [{record.timestamp:.3f}s] {record.plugin_name}.{record.action}")
    
    # 生成文档
    print("\n5. 生成文档...")
    doc_files = framework.generate_documentation()
    if doc_files:
        print(f"✓ 生成了 {len(doc_files)} 个文档文件")
    
    # 保存录制
    print("\n6. 保存录制...")
    if framework.save_recording("./recordings/demo_recording.json"):
        print("✓ 录制保存成功")
    
    print("\n=== 演示完成 ===")